using UnityEngine;
using UnityEngine.EventSystems;

/// <summary>
///     ����
/// </summary>
public class MenuManager : MonoBehaviour
{
    private static MenuManager instance;

    [Header("Menu object")] [SerializeField]
    private GameObject mainMenuCanvas;

    [SerializeField] private GameObject settingMenuCanvas;

    [Header("Status object")] [SerializeField]
    private GameObject statusBarCanvas;

    [Header("First selected Option")] [SerializeField]
    private GameObject _mainMenuFirst;

    [SerializeField] private GameObject _statusBarFirst;

    private bool isMenuOpen;

    private bool isPaused;
    private bool isStatusOpen;

    public static MenuManager Instance
    {
        get
        {
            if (instance == null)
                //instance = FindObjectOfType<MenuManager>() as MenuManager;
                instance = new MenuManager();
            return instance;
        }
    }

    private void Start()
    {
        mainMenuCanvas.SetActive(false);
        settingMenuCanvas.SetActive(false);
        statusBarCanvas.SetActive(false);
    }

    private void Update()
    {
        if (LightInputManager.Instance.MenuOpenCloseInput)
        {
            if (!isMenuOpen)
            {
                isMenuOpen = true;
                Pause();
            }
            else
            {
                isMenuOpen = false;
                UnPause();
            }
        }
        else if (LightInputManager.Instance.StatusOpenCloseInput)
        {
            if (!isStatusOpen)
            {
                isStatusOpen = true;
                Pause();
            }
            else
            {
                isStatusOpen = false;
                UnPause();
            }
        }
    }

    public void Pause()
    {
        isPaused = true;
        Time.timeScale = 0f;

        if (isMenuOpen) OpenMainMenu();
        if (isStatusOpen) OpenStatusBar();
    }

    public void UnPause()
    {
        isPaused = false;
        Time.timeScale = 1f;

        if (!isMenuOpen) CloseAllMenu();
        if (!isStatusOpen) CloseStatusBar();
    }

    private void OpenMainMenu()
    {
        mainMenuCanvas.SetActive(true);
        settingMenuCanvas.SetActive(false);

        EventSystem.current.SetSelectedGameObject(_mainMenuFirst);
    }

    private void CloseAllMenu()
    {
        mainMenuCanvas.SetActive(false);
        settingMenuCanvas.SetActive(false);
    }

    private void OpenStatusBar()
    {
        statusBarCanvas.SetActive(true);

        EventSystem.current.SetSelectedGameObject(_statusBarFirst);
    }

    private void CloseStatusBar()
    {
        statusBarCanvas.SetActive(false);
    }
}